namespace EyeOpen.Data.Nhibernate
{
	using System;
	using System.Collections;
	using System.Collections.Generic;
	using System.Linq;
	using System.Linq.Expressions;

	using NHibernate;
	using NHibernate.Linq;

	internal class NhibernateRepository<T> 
		: IRepository<T>
		where T : class
	{
		private readonly ISession session;

		private readonly IQueryable<T> queryable;

		public NhibernateRepository(ISession session)
		{
			this.session = session;
			queryable = session.Query<T>().AsQueryable();
		}

		public Expression Expression
		{
			get
			{
				return queryable.Expression;
			}
		}

		public Type ElementType
		{
			get
			{
				return queryable.ElementType;
			}
		}

		public IQueryProvider Provider
		{
			get
			{
				return queryable.Provider;
			}
		}

		public int Count
		{
			get
			{
				return queryable.Count();
			}
		}

		public bool IsReadOnly
		{
			get
			{
				return false;
			}
		}

		public IEnumerator<T> GetEnumerator()
		{
			return queryable.GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}

		public void Add(T entity)
		{
			session.Save(entity);
		}

		public bool Remove(T entity)
		{
			session.Delete(entity);

			return true;
		}

		public void Update(T entity)
		{
			session.Merge(entity);
		}

		/// <exception cref="NotSupportedException"></exception>
		public void Clear()
		{
			throw new NotSupportedException();
		}

		/// <exception cref="NotSupportedException"></exception>
		public bool Contains(T item)
		{
			throw new NotSupportedException();
		}

		/// <exception cref="NotSupportedException"></exception>
		public void CopyTo(T[] array, int arrayIndex)
		{
			throw new NotSupportedException();
		}
	}
}